package com.example.hospitalsystem.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hospitalsystem.mapper.AdminMapper;
import com.example.hospitalsystem.pojo.dto.admin.AdminDto;
import com.example.hospitalsystem.pojo.entity.Admin;
import com.example.hospitalsystem.pojo.entity.User;
import com.example.hospitalsystem.result.Result;
import com.example.hospitalsystem.service.AdminService;
import com.example.hospitalsystem.utils.JwtHelper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public Result<Object> completeEditAdmin(AdminDto adminDto) {
        String token=request.getHeader("Authorization");
        Integer user_id=jwtHelper.getUserId(token);

        Admin admin=new Admin();
        admin.setUserId(user_id);
        BeanUtils.copyProperties(adminDto,admin);
        this.save(admin);
        return Result.build(admin,200,"完善管理员信息成功");
    }

    @Override
    public Result<Object> editAdminInfo(Admin admin) {
        String token=request.getHeader("Authorization");
        Integer userId=jwtHelper.getUserId(token);
        admin.setUserId(userId);

        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper=new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getUserId,userId);
        Admin admin1=baseMapper.selectOne(adminLambdaQueryWrapper);
        if(admin1==null){
            this.save(admin);
            return Result.build(200,"添加管理员信息成功");
        }

        LambdaUpdateWrapper<Admin> adminLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        adminLambdaUpdateWrapper.eq(Admin::getUserId,userId);

        this.update(admin,adminLambdaUpdateWrapper);

        return Result.build(200,"修改管理员信息成功");
    }

    @Override
    public Result<Object> getAdminOne() {
        String token=request.getHeader("Authorization");
        Integer userId=jwtHelper.getUserId(token);

        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper=new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getUserId,userId);

        Admin admin=baseMapper.selectOne(adminLambdaQueryWrapper);
        if (admin==null){
            return Result.build("占时没有管理员详细信息");
        }
        return Result.build(admin,200,"返回管理员个人信息成功");
    }
}
